#include "ExportWorker.h"
#include "ExportDialog.h"
#include <unistd.h>
#include <fcntl.h>
#include <Database.h>
ExportWorker *ExportWorker::getInstance() {
    static ExportWorker singleton{};
    return &singleton;
}

void ExportWorker::startWork(int number)
{

    PatientInfo *info =  Database::getInstance()->queryPatient(number);
    if(info->number<0) {
        return;
    }
    g_number = info->id;
    start(LowPriority);
}

void ExportWorker::stopWork()
{

}

ExportWorker::ExportWorker()
{
    QObject::connect(this, &ExportWorker::startWorkSignal, ExportDialog::getInstance(), &ExportDialog::busySlot);
    QObject::connect(this, &ExportWorker::completeWorkSignal, ExportDialog::getInstance(), &ExportDialog::completeSlot);
    QObject::connect(this, &ExportWorker::exportErrorSignal, ExportDialog::getInstance(), &ExportDialog::exportErrorSlot);
}

void ExportWorker::exportWork()
{
#ifdef arm
    QString path = QString("/home/root/data/patient_%1").arg(g_number);

    QStringList cmd;
    cmd << QString("cd /run/media/sda*");
    cmd << QString("cp %1 . -rf").arg(path);
    cmd << QString("cd /home/root");
    QString command = cmd.join(";");
    qDebug()<<"export cmd:"<<command;

    int status = system(command.toUtf8().data());
    if((status < 0) || (!WIFEXITED(status)) || (0 != WEXITSTATUS(status))) {
        qDebug()<<"delete medio failed";
        emit exportErrorSignal();
        return;
    }
    sync();
    sleep(1);
#endif
}

void ExportWorker::run()
{
    qDebug()<<"ExportWorker running";
    emit startWorkSignal();
    exportWork();
    emit completeWorkSignal();
}
